<template>
    <FormDrawer ref="formDrawerRef" title="推荐商品" confirmText="关联" @submit="handleSubmit">
        <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" />
            <el-table-column prop="cover" label="商品封面">
                <template #default="{row}">
                    <el-image class="w-[80px] h-[80px]" :src="row.cover" fit="fill" :lazy="true"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" width="180" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="primary" text size="small" @click="handleDeleteCategoryItem(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </FormDrawer>
    <ChooseGoods ref="chooseGoodsRef" />
</template>
<script setup>
import { ref } from "vue";
import ChooseGoods from '~/components/ChooseGoods.vue'
import { getCategoryItemList, deleteCategoryItem, addCategoryItem } from '~/api/category.js'
import FormDrawer from "~/components/FormDrawer.vue";
import { toast } from '~/composables/util.js'
const formDrawerRef = ref(null)
const category_id = ref(0)
const tableData = ref([])
const loading = ref(false)
const open = (item) => {
    category_id.value = item.id
    getData().then(res => {
        console.log(res);
        formDrawerRef.value.open()
    })
}

function getData () {
    loading.value = true
    return getCategoryItemList(category_id.value).then(res => tableData.value = res).finally(() => loading.value = false)
}

function handleDeleteCategoryItem (item) {
    loading.value = true
    deleteCategoryItem(item.id).then(res => {
        toast('删除成功')
        getData()
    }).finally(() => {
        loading.value = false
    })
}

let chooseGoodsRef = ref(null)
const handleSubmit = () => {
    chooseGoodsRef.value.open((goods_ids) => {
        formDrawerRef.value.showLoading()
        console.log(category_id.value);
        addCategoryItem({ category_id: category_id.value, goods_ids }).then(res => {
            toast('关联成功')
            getData()
        }).finally(() => {
            formDrawerRef.value.hideLoading()
        })
    })
}
defineExpose({
    open
})
</script>